package common.cos;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.meta.InsertOnly;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;
import java.util.Date;


/**
 * Created by xuweijie on 2017/6/7.
 */
public class FileUploadCos {
    private long appId;
    private String secretId;
    private String secretKey;
    private String bucketName;
    private String cosPath;
    private COSClient cosClient;

    public COSClient FileUploadCos() {
        // 初始化秘钥信息
        Credentials cred=new Credentials(appId,secretId,secretKey);
        // 初始化客户端配置
        ClientConfig clientConfig = new ClientConfig();
        // 设置bucket所在的区域，比如华南园区：gz； 华北园区：tj；华东园区：sh ；
        clientConfig.setRegion("gz");
        // 初始化cosClient
        return new COSClient(clientConfig, cred);
    }

    /**
     *上傳照片
     * @param localpath:本地上傳文件的路徑
     * @return
     */
    public String uploadFile(String localpath,String fileName){
        cosClient=FileUploadCos();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        cosPath+=suffix;
        UploadFileRequest uploadFileRequest=new UploadFileRequest(bucketName,cosPath,localpath);
        uploadFileRequest.setInsertOnly(InsertOnly.OVER_WRITE);//文件已存在則覆蓋原文件
//        return parseData(cosClient.uploadFile(uploadFileRequest));
        return cosClient.uploadFile(uploadFileRequest);
    }

    /**
     *
     * @param data
     * @return
     * 解析獲取CDN鏈接
     */
    public String parseData(String data){
        JSONObject obj = JSON.parseObject(data);
        JSONObject object2 = (JSONObject) obj.get("data");
        return object2.getString("access_url");
    }


    public long getAppId() {
        return appId;
    }

    public void setAppId(long appId) {
        this.appId = appId;
    }

    public String getSecretId() {
        return secretId;
    }

    public void setSecretId(String secretId) {
        this.secretId = secretId;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    public String getCosPath() {
        return cosPath;
    }

    public void setCosPath(String cosPath) {
        this.cosPath = cosPath;
    }

    @Override
    public String toString() {
        return "FileUploadCos{" +
                "appId=" + appId +
                ", secretId='" + secretId + '\'' +
                ", secretKey='" + secretKey + '\'' +
                ", bucketName='" + bucketName + '\'' +
                ", cosPath='" + cosPath + '\'' +
                ", cosClient=" + cosClient +
                '}';
    }
}
